﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WHMS.EntityClasses;
using WMS.HelperClasses;
using WHMS.HelperClasses;
using SD.LLBLGen.Pro.ORMSupportClasses;
using WHMS;

namespace WMS
{
	public partial class RemoveItemsFromTransferForm : Form
	{
		TransferRequestEntity _currentRequest;
		WithdrawTransactionEntity _currentWithdrawTransaction;
		DataMngrFormBase<TransferRequestItemEntity> _tranItemsForm;
		List<ErrorProvider> _errorProviders;

		public RemoveItemsFromTransferForm()
		{
			InitializeComponent();

			_currentRequest = new TransferRequestEntity();
			_currentWithdrawTransaction = new WithdrawTransactionEntity();

			LoadData();

			_errorProviders = new List<ErrorProvider>();

			EnableDisableControls();
		}		

		void LoadData()
		{
			DALHelper.FetchCollection(_removeTypes, null, null, new SortExpression(WithdrawalTypeFields.Order | SortOperator.Ascending));

			FormsHelper.LoadComboBox(ProjectsDDL, ProjectFields.Id, ProjectFields.Name, (x, y) => DALHelper.GetDynamicList(x, y, null));
			FormsHelper.LoadComboBox(StoresDDL, StoreFields.Id, StoreFields.Name, () => Business.GetStoresForKeeper());			
			FormsHelper.LoadComboBox(AccountantsDDL, UserFields.Id, UserFields.Name, (x, y) => Business.GetAccountants(x, y));
			FormsHelper.LoadComboBox(ContractorsDDL, ContractorFields.Id, ContractorFields.Name, (x, y) => DALHelper.GetDynamicList(x, y, null));

			FormsHelper.CheckStoresAndProjects(StoresDDL.Items, ProjectsDDL.Items, new List<Control>() { _transItemsGrid, SaveBtn }, NoStoresLbl, NoProjectsLbl);
		}

		private void SaveBtn_Click(object sender, EventArgs e)
		{
		    Save();
		}

	    private void Save()
	    {
	        if (!ValidateForm())
	            return;

	        if (!_currentWithdrawTransaction.IsNew)
	        {
	            if ((bool)DALHelper.GetValue(WithdrawTransactionFields.IsPriced, WithdrawTransactionFields.Id, _currentWithdrawTransaction.Id))
	            {
	                RetrieveTransaction();
	                return;
	            }
	        }

	        var transItems = new EntityCollection<TransactionItemEntity>();
	        var transItemsToDelete = new EntityCollection<TransactionItemEntity>();

	        if (_currentWithdrawTransaction.IsNew)
	        {
	            _currentWithdrawTransaction.AccountantId = GetSelectedAccountantId();// _currentRequest.AccountantId;
	            //_currentWithdrawTransaction.ContractorId = _currentRequest.ContractorId;
	            _currentWithdrawTransaction.Wrnumber = _currentRequest.RequestNumber;
	            _currentWithdrawTransaction.Type = "T";// _currentRequest.Type;
	            _currentWithdrawTransaction.Recipient = RecipientTB.Text;

	            var transaction = new TransactionEntity()
	                                  {
	                                      ProjectId = _currentRequest.ProjectId,
	                                      StoreId = GetSelectedStoreId(),
	                                      PermitNumber = PermitNumberTB.Text,
	                                      CreatedBy = UserInfo.UserId,
	                                      Date = WithdrawlDateDTP.Value.Date,
	                                      Type = "Withdraw"
	                                  };

	            _currentWithdrawTransaction.Transaction = transaction;
	        }
	        else
	        {
	            DALHelper.FetchCollection(transItems, new RelationPredicateBucket(TransactionItemFields.TransactionId == _currentWithdrawTransaction.TransactionId));
	        }

			
	        foreach (TransferRequestItemEntity item in _requestItems)
	        {
	            if (item.QuantityToBeWithdrawn > 0 && item.NewShelfId > 0)
	            {
	                var q = (from t in transItems
	                         where t.RequestItemId == item.Id
	                         select t).FirstOrDefault();

	                TransactionItemEntity transItem;

	                if (q == null)
	                {
	                    transItem = new TransactionItemEntity();
	                }
	                else
	                {
	                    transItem = q;
	                }					

	                transItem.ShelfId = item.NewShelfId;
	                transItem.StoreId = _currentWithdrawTransaction.Transaction.StoreId.Value;
	                transItem.ItemId = item.ItemId;
	                transItem.Quantity = item.QuantityToBeWithdrawn;
	                transItem.RequestItemId = item.Id;

	                var price = Business.GetItemPrice(_currentRequest.ProjectId, transItem.StoreId, item.NewShelfId, item.ItemId);
	                transItem.UnitPrice = price;
	                transItem.SellingPrice = price;// Business.GetItemCost(transItem.StoreId, transItem.ShelfId.Value, transItem.ItemId);

	                item.SellingPrice = price;
	                item.WithdawedQuantity = item.QuantityToBeWithdrawn;

	                _currentWithdrawTransaction.Transaction.TransactionItems.Add(transItem);
	            }
	            else
	            {
	                var q = (from t in transItems
	                         where t.RequestItemId == item.Id
	                         select t).FirstOrDefault();

	                if (q != null)
	                {
	                    transItemsToDelete.Add(q);
	                }
	            }
	        }

	        DALHelper.DeleteCollection(transItemsToDelete);
	        if (DALHelper.SaveEntity(_currentWithdrawTransaction, true))
	        {
	            _currentRequest.IsProcessed = true;
	            DALHelper.SaveEntity(_currentRequest);
	            DALHelper.SaveCollection(_requestItems);

	            RetrieveTransaction();
	            MessageBox.Show("تم الحفظ بنجاح.");
	        }
	    }

	    private bool ValidateForm()
		{
			var isValid = true;

			var controls = new List<TextBox>();
			//controls.Add(RecipientTB);
			controls.Add(WRNumberTB);
			controls.Add(PermitNumberTB);

			if (_errorProviders == null)
			{
				_errorProviders = new List<ErrorProvider>();
			}
			else
			{
				foreach (var errorProvider in _errorProviders)
				{
					errorProvider.Clear();
					errorProvider.Dispose();
				}
			}
			foreach (var tb in controls)
			{
				if (string.IsNullOrEmpty(tb.Text.Trim()))
				{
					var errorProvider = new ErrorProvider(this);
					_errorProviders.Add(errorProvider);

					errorProvider.SetError(tb, "يجب إدخال قيمة");
					errorProvider.RightToLeft = true;

					isValid = false;
					continue;
				}
			}

			if (!ValidatePermitNumber())
				isValid = false;

			//_tranItemsForm.ValidateCollection();
			if (!_tranItemsForm.IsDataValid())
				isValid = false;

			if (_requestItems.Count <= 0)
			{
				isValid = false;
				MessageBox.Show("يجب إضافة أصناف", "خطأ فى الحفظ", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}

			return isValid;
		}

		private void StoresDDL_SelectedIndexChanged(object sender, EventArgs e)
		{
			//ResetTransactionItems();

			//if (StoresDDL.SelectedItem == null)
			//	return;
			
			//LoadShelves(GetSelectedStoreId());
			//GetShelves(null);
		}

		private void _transItemsGrid_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
		{
		}

		private void LoadRequestItems(int requestId)
		{
			if (_tranItemsForm != null)
			{
				_tranItemsForm.Dispose();
				_tranItemsForm = null;
			}

			var prefetch = new PrefetchPath2(EntityType.TransferRequestItemEntity);
			prefetch.Add(TransferRequestItemEntity.PrefetchPathItem).SubPath.Add(ItemEntity.PrefetchPathUnit_);

			var label = new Label();
			_tranItemsForm = new DataMngrFormBase<TransferRequestItemEntity>(_requestItems, _transItemsGrid, bindingSource1, new Button(), label, label, new RelationPredicateBucket(TransferRequestItemFields.TransferRequestId == requestId), prefetch);
			_tranItemsForm.SetNumericFields(new List<int> { QuantityColumn.Index});
			//_tranItemsForm.SetMandatoryFields(new List<int>() {ShelfColumn.Index, QuantityColumn.Index});
			_tranItemsForm.RaiseSelectedChangedEventForComboBoxColumns(new List<int> { ShelfColumn.Index });
			_tranItemsForm.ComboboxColumnSelectionChanged += new DataMngrFormBase<TransferRequestItemEntity>.RaiseComboboxColumnSelectionChanged(_tranItemsForm_ComboboxColumnSelectionChanged);
			_tranItemsForm.RowValidating += new DataMngrFormBase<TransferRequestItemEntity>.RaiseRowValidating(_tranItemsForm_RowValidating);
		}

		private void _tranItemsForm_RowValidating(int rowIndex, ref bool hasErrors)
		{			
			var availableQuantityCell = _transItemsGrid.Rows[rowIndex].Cells[AvailableAmountColumn.Index];
			var availaleQuantity = (availableQuantityCell == null) ? 0 : availableQuantityCell.Value;

			var remainderQuantityCell = _transItemsGrid.Rows[rowIndex].Cells[RemainderQuantityColumn.Index];
			var remainderQuantity = (remainderQuantityCell == null) ? 0 : remainderQuantityCell.Value;

			var quantityCell = _transItemsGrid.Rows[rowIndex].Cells[QuantityColumn.Index];
			var quantity = quantityCell.Value;

			if (quantity == null)
				return;

			//if ((decimal)quantity <= 0)
			//{
			//    quantityCell.ErrorText = "الكمية المراد صرفها يجب أن تكون رقم موجب.";
			//    hasErrors = true;
			//    return;
			//}

			if ((availaleQuantity != null && (decimal)quantity <= (decimal)availaleQuantity) && (decimal)quantity <= (decimal)remainderQuantity)
			{
				quantityCell.ErrorText = string.Empty;
				return;
			}

			if ((decimal)quantity > (decimal)remainderQuantity)
			{
				quantityCell.ErrorText = "الكمية المراد صرفها يجب أن لا تتعدى الكمية المتبقية من الطلب.";
				hasErrors = true;
				return;
			}

			quantityCell.ErrorText = "الكمية المراد صرفها يجب أن لا تتعدى الكمية المتاحة فى المخزن.";
			hasErrors = true;
		}

		private void _tranItemsForm_ComboboxColumnSelectionChanged(object selectedValue)
		{
			if (selectedValue == null)
				return;

			if (selectedValue is int)
			{
				if (_transItemsGrid.CurrentCell.ColumnIndex == ShelfColumn.Index)
				{
					var itemId = (int)_transItemsGrid.CurrentRow.Cells[ItemIdColumn.Index].Value;
					var shelfId = (int)selectedValue;

					//_transItemsGrid.CurrentRow.Cells[AvailableAmountColumn.Index].Value = Business.GetItemBalance(GetSelectedProjectId(), _currentWithdrawTransaction.Transaction.StoreId.Value, shelfId, itemId, _showStoppedProjectsItemsCB.Checked);
					_transItemsGrid.CurrentRow.Cells[AvailableAmountColumn.Index].Value = Business.GetItemBalance(GetSelectedProjectId(), GetStoreId(), shelfId, itemId, _showStoppedProjectsItemsCB.Checked);
					//_transItemsGrid.CurrentRow.Cells[4].Value = Business.GetItemPrice(GetSelectedStoreId(), shelfId, itemId);
				}
			}
		}

		#region shelves
		private void LoadShelves(int storeId)
		{			
			foreach (DataGridViewRow row in _transItemsGrid.Rows)
			{
				var control = (_transItemsGrid[ShelfColumn.Index, row.Index] as DataGridViewComboBoxCell);
				LoadShelves(control, row.Index, storeId);
			}

			var index = 0;
			foreach (TransferRequestItemEntity item in _requestItems)
			{
				decimal availableQuantity = 0;
				string shelfCode = string.Empty;
				item.NewShelfId = Business.GetWithdrawShelfId(_currentRequest.ProjectId, storeId, item.ItemId, item.RemainderQuantity, "T", out availableQuantity, out shelfCode);
				item.AvailableQantity = availableQuantity;
				item.NewShelfCode = shelfCode;
				//_transItemsGrid.CurrentRow.Cells[AvailableAmountColumn.Index].Value = Business.GetItemBalance(_currentRequest.ProjectId, storeId, item.NewShelfId, item.ItemId, _showStoppedProjectsItemsCB.Checked);
				//item.AvailableQantity = Business.GetItemBalance(_currentRequest.ProjectId, storeId, item.NewShelfId, item.ItemId, _showStoppedProjectsItemsCB.Checked);
				_transItemsGrid.Rows[index].Cells[NewShelfCode.Index].Value = item.NewShelfCode;
				_transItemsGrid.Rows[index].Cells[NewShelfCode.Index].Selected = true;
				_transItemsGrid.Rows[index].Cells[NewShelfCode.Index].Selected = false;
				
				_transItemsGrid.Rows[index].Cells[AvailableAmountColumn.Index].Value = item.AvailableQantity;
				_transItemsGrid.Rows[index].Cells[AvailableAmountColumn.Index].Selected = true;
				_transItemsGrid.Rows[index].Cells[AvailableAmountColumn.Index].Selected = false; 
				index++;
			}
			
			if (_transItemsGrid.Rows.Count > 0)
				_transItemsGrid.Rows[0].Cells[QuantityColumn.Index].Selected = true; 
		}
		private void LoadShelves(DataGridViewComboBoxCell control, int rowIndex, int storeId)
		{
			var itemIdValue = _transItemsGrid.Rows[rowIndex].Cells[ItemIdColumn.Index].Value;
			if (itemIdValue == null)
				return;

			control.DisplayMember = ShelfFields.Code.Name;
			control.ValueMember = ShelfFields.Id.Name;

			var shelves = GetShelves((int)itemIdValue, storeId);
			var bindingsource = new BindingSource();
			bindingsource.DataSource = shelves;
			control.DataSource = bindingsource;

			if (shelves.Count <= 0)
			{
			    //MessageBox.Show("لا يوجد رصيد بالمخزن المختار", "تنبيه", MessageBoxButtons.OK, MessageBoxIcon.Warning);
				_transItemsGrid.Rows[rowIndex].Cells[ShelfColumn.Index].ErrorText = "لا يوجد رصيد بالمخزن";
			}
			else
			{
				_transItemsGrid.Rows[rowIndex].Cells[ShelfColumn.Index].ErrorText = string.Empty;
			}
		}
		private EntityCollection<ShelfEntity> GetShelves(int itemId, int storeId)
		{
			var filter = GetShelvesFilter(itemId, storeId);


			var shelves = new EntityCollection<ShelfEntity>();
			DALHelper.FetchCollection(shelves, filter);
			return shelves;
		}
		private RelationPredicateBucket GetShelvesFilter(int itemId, int storeId)
		{
			var shelfFilter = new PredicateExpression(StoreShelfBalanceFields.ItemId == itemId);
			shelfFilter.Add(StoreShelfBalanceFields.StoreId == storeId);

			var projectFilter = new PredicateExpression(StoreShelfBalanceFields.ProjectId == GetSelectedProjectId());
			if (_showStoppedProjectsItemsCB.Checked)
			{
				projectFilter.AddWithOr(new FieldCompareSetPredicate(StoreShelfBalanceFields.ProjectId, null, ProjectFields.Id, null, SetOperator.In, new PredicateExpression(ProjectFields.Status == "جارى"), true));
				projectFilter.AddWithOr(new FieldCompareSetPredicate(StoreShelfBalanceFields.ProjectId, null, ProjectFields.Id, null, SetOperator.In, new PredicateExpression(ProjectFields.IsGeneral == true)));
			}
			shelfFilter.Add(projectFilter);

			var filter = new RelationPredicateBucket(new FieldCompareSetPredicate(ShelfFields.Id, null, StoreShelfBalanceFields.ShelfId, null, SetOperator.In, shelfFilter));
			filter.PredicateExpression.Add(ShelfFields.StoreId == storeId);
			return filter;
		}
		#endregion

		private int GetSelectedStoreId()
		{
			if (StoresDDL.SelectedItem == null)
				return 0;

			return (int)((System.Data.DataRowView)(StoresDDL.SelectedItem)).Row.ItemArray[0];		
		}
		private int GetStoreId()
		{
			if (_currentWithdrawTransaction.Transaction == null)
			{
				return GetSelectedStoreId();
			}

			if (_currentWithdrawTransaction.Transaction.StoreId.HasValue)
				return _currentWithdrawTransaction.Transaction.StoreId.Value;

			return 0;
		}
		private int GetSelectedProjectId()
		{
			if (ProjectsDDL.SelectedItem == null)
				return 0;
			return (int)((System.Data.DataRowView)(ProjectsDDL.SelectedItem)).Row.ItemArray[0];
		}
		private int GetSelectedAccountantId()
		{
			if (AccountantsDDL.SelectedItem == null)
				return 0;
			return (int)((System.Data.DataRowView)(AccountantsDDL.SelectedItem)).Row.ItemArray[0];
		}

		private bool ValidatePermitNumber()
		{
			return FormsHelper.ValidatePermitNumber(this, PermitNumberTB, _errorProviders, "Withdraw", _currentWithdrawTransaction.TransactionId);
		}

		private void PermitNumberTB_Leave(object sender, EventArgs e)
		{
			ValidatePermitNumber();
		}

		private void RetrieveRequestBtn_Click(object sender, EventArgs e)
		{
			RetrieveRequest();
		}

		private void RetrieveBtn_Click(object sender, EventArgs e)
		{
			RetrieveTransaction();
		}

		private void NewBtn_Click(object sender, EventArgs e)
		{
			ResetForm();
		}

		private void RetrieveTransaction()
		{			
			if (string.IsNullOrEmpty(PermitNumberTB.Text.Trim()))
				return;

			//var requestTypes = new string[3] { "G", "S", "M" };

			var collection = new EntityCollection<WithdrawTransactionEntity>();
			var filter = new RelationPredicateBucket(TransactionFields.PermitNumber == PermitNumberTB.Text.Trim());
			filter.Relations.Add(WithdrawTransactionEntity.Relations.TransactionEntityUsingTransactionId);
			filter.PredicateExpression.Add(
				new FieldCompareSetPredicate(WithdrawTransactionFields.Wrnumber, null, TransferRequestFields.RequestNumber, null, SetOperator.In, null, false));

			var prefetch = new PrefetchPath2(EntityType.WithdrawTransactionEntity);
			prefetch.Add(WithdrawTransactionEntity.PrefetchPathTransaction);

			DALHelper.FetchCollection(collection, filter, prefetch);

			if (collection.Count <= 0)
			{
				//_currentWithdrawTransaction = new WithdrawTransactionEntity();
				ResetForm();
			}
			else
			{
				_currentWithdrawTransaction = collection[0];
				RetrieveRequest(_currentWithdrawTransaction.Wrnumber);

				_WithdrawBS.DataSource = _currentWithdrawTransaction;
				_TransBS.DataSource = _currentWithdrawTransaction.Transaction;


				var transItems = new EntityCollection<TransactionItemEntity>();

				DALHelper.FetchCollection(transItems, new RelationPredicateBucket(TransactionItemFields.TransactionId == _currentWithdrawTransaction.TransactionId));
				foreach (TransferRequestItemEntity requestItem in _requestItems)
				{
					var q = (from t in transItems
							where t.ItemId == requestItem.ItemId
							select t).FirstOrDefault();

					if (q == null)
						continue;

					requestItem.NewShelfId = q.ShelfId.Value;
					requestItem.QuantityToBeWithdrawn = q.Quantity;
					requestItem.AvailableQantity = Business.GetItemBalance(_currentWithdrawTransaction.Transaction.ProjectId, _currentWithdrawTransaction.Transaction.StoreId.Value, requestItem.NewShelfId, requestItem.ItemId, _showStoppedProjectsItemsCB.Checked);
				}
			}

			//_WithdrawBS.DataSource = _currentWithdrawTransaction;
			//_TransBS.DataSource = _currentWithdrawTransaction.Transaction;

			ValidatePermitNumber();

			EnableDisableControls();
		}

		private void RetrieveRequest()
		{
			var requestNumber = WRNumberTB.Text;
			ResetForm();
			RetrieveRequest(requestNumber);
			EnableDisableControls();
		}
		private void RetrieveRequest(string requestNumber)
		{
			if (string.IsNullOrEmpty(requestNumber.Trim()))
				return;

			var collection = new EntityCollection<TransferRequestEntity>();

			var filter = new RelationPredicateBucket(TransferRequestFields.RequestNumber == requestNumber.Trim());

			DALHelper.FetchCollection(collection, filter);

			if (collection.Count <= 0)
			{
				_currentRequest = new TransferRequestEntity();
				_WRequestBS.DataSource = _currentRequest;
			}
			else
			{
				_currentRequest = collection[0];
				_WRequestBS.DataSource = _currentRequest;
                SetTransferRequestData(_currentRequest);
			}
			//_requestItems.Clear();
			//DALHelper.FetchCollection(_requestItems, new RelationPredicateBucket(WithdrawRequestItemFields.WithdrawRequestId == _currentRequest.Id));			
			LoadRequestItems(_currentRequest.Id);
			LoadShelves(GetSelectedStoreId());//(GetStoreId());
			//EnableDisableControls();
		    
		}

	    private void SetTransferRequestData(TransferRequestEntity currentRequest)
	    {
	        var toProj = currentRequest.ToProjectId != null
	                         ? GetProjectById(currentRequest.ToProjectId.Value)
	                         : null;

            txtToProject.Text = toProj != null
                                            ? toProj.Name
                                            : string.Empty;

            var fromStore = GetStoreById(currentRequest.FromStoreId);
            txtFromStore.Text = fromStore != null
                                            ? fromStore.Name
                                            : string.Empty;
            var toStore = GetStoreById(currentRequest.ToStoreId);
	        txtToStore.Text = toStore != null
	                                    ? toStore.Name
	                                    : string.Empty;
	    }

        private StoreEntity GetStoreById(int id)
        {
            var collection = new EntityCollection<StoreEntity>();

            var filter = new RelationPredicateBucket(StoreFields.Id == id);

            DALHelper.FetchCollection(collection, filter);

            if (collection.Count != 0)
                return collection.First();

            return null;
        }


        private ProjectEntity GetProjectById(int id)
        {
            var collection = new EntityCollection<ProjectEntity>();

            var filter = new RelationPredicateBucket(ProjectFields.Id == id);

            DALHelper.FetchCollection(collection, filter);

            if (collection.Count != 0)
                return collection.First();

            return null;
        }
	    private void ResetForm()
		{
			_currentRequest = new TransferRequestEntity();
			_currentWithdrawTransaction = new WithdrawTransactionEntity();
			_currentWithdrawTransaction.Transaction = new TransactionEntity();
			_requestItems.Clear();

			_WithdrawBS.DataSource = _currentWithdrawTransaction;
			_TransBS.DataSource = _currentWithdrawTransaction.Transaction;
			_WRequestBS.DataSource = _currentRequest;

	        txtToProject.Text = txtFromStore.Text = txtToStore.Text = string.Empty;

			EnableDisableControls();
		}

		void EnableDisableControls()
		{
            if (_currentWithdrawTransaction.TransactionStatus == 1)
            {
                _alreadyPricedLbl.Text = "* إذن الصرف تم حفظه نهائيا ويمكن تسعيره فقط  !";
            }

			var isPriced = (_currentWithdrawTransaction.IsPriced.HasValue) ? _currentWithdrawTransaction.IsPriced.Value : false;
            var isSubmitted = _currentWithdrawTransaction.TransactionStatus > 0;
            //var isEditable = !((!isPriced) || isSubmitted);

            if(isPriced || isSubmitted)
            {
                _transItemsGrid.Enabled = false;
                BtnSubmit.Enabled = SaveBtn.Enabled = false;
                _alreadyPricedLbl.Visible = true;
                bindingNavigator1.Enabled = false;
                RecipientTB.Enabled = false;
                WithdrawlDateDTP.Enabled = false;
            }
            else
            {
                _transItemsGrid.Enabled = true;
                BtnSubmit.Enabled = SaveBtn.Enabled = true;
                _alreadyPricedLbl.Visible = false;
                bindingNavigator1.Enabled = true;
                RecipientTB.Enabled = true;
                WithdrawlDateDTP.Enabled = true;
            }

			//_transItemsGrid.Enabled = !isPriced || !isSubmitted;
            //BtnSubmit.Enabled = SaveBtn.Enabled = !isPriced || !isSubmitted;

		    //bindingNavigator1.Enabled = !isPriced || !isSubmitted;
			//_alreadyPricedLbl.Visible = isPriced;
			//StoresDDL.Enabled = !isPriced;
			//RecipientTB.Enabled = !isPriced || !isSubmitted;
			//WithdrawlDateDTP.Enabled = !isPriced || !isSubmitted;
			_showStoppedProjectsItemsCB.Enabled = !isPriced;

			NewBtn.Enabled = !_currentWithdrawTransaction.IsNew;
			DeleteBtn.Enabled = !(_currentWithdrawTransaction.IsNew || isPriced);

			_showStoppedProjectsItemsCB.Checked = false;// (_currentRequest.Type == "G");
			_showStoppedProjectsItemsCB.Enabled = true;// (_currentRequest.Type != "G");
		}

		private void _transItemsGrid_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
		{
			if (e.ColumnIndex != QuantityColumn.Index)
				return;

			var itemIdValue = _transItemsGrid.Rows[e.RowIndex].Cells[ItemIdColumn.Index].Value;
			if (itemIdValue == null)
				return;

			var form = new UnitConverterForm((int)itemIdValue);
			if (form.ShowDialog() == DialogResult.OK)
			{
				_transItemsGrid.SuspendLayout();
				_transItemsGrid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = form.Value;
				_transItemsGrid.UpdateCellValue(e.ColumnIndex, e.RowIndex);
				_transItemsGrid.ResumeLayout(true);
			}

		}

		private void SearchBtn_Click(object sender, EventArgs e)
		{
			//var requestTypes = new string[3]{"G","S","M"};

			var filter = new RelationPredicateBucket(TransactionFields.Type == "Withdraw");
			filter.Relations.Add(TransactionEntity.Relations.ProjectEntityUsingProjectId);
			filter.Relations.Add(TransactionEntity.Relations.WithdrawTransactionEntityUsingTransactionId);
			filter.PredicateExpression.Add(
				new FieldCompareSetPredicate(WithdrawTransactionFields.Wrnumber, null, TransferRequestFields.RequestNumber, null, SetOperator.In, null, false));

			var searchForm = new SearchForm(TransactionFields.PermitNumber, TransactionFields.ProjectId, TransactionFields.Date, filter, null);
			if (searchForm.ShowDialog() == DialogResult.OK)
			{
				PermitNumberTB.Text = searchForm.SelectedNumber;
				RetrieveTransaction();
			}
		}

		private void SearchRequestBtn_Click(object sender, EventArgs e)
		{
			var filter = new RelationPredicateBucket();
			filter.Relations.Add(TransferRequestEntity.Relations.ProjectEntityUsingProjectId);
			//filter.PredicateExpression.Add(ProjectFields.IsGeneral == false);

			var searchForm = new SearchForm(TransferRequestFields.RequestNumber, TransferRequestFields.ProjectId, TransferRequestFields.Date, filter, () => Business.GetRunningProjects());
			if (searchForm.ShowDialog() == DialogResult.OK)
			{
				WRNumberTB.Text = searchForm.SelectedNumber;
				RetrieveRequest();
			}
		}

		private void DeleteBtn_Click(object sender, EventArgs e)
		{
			var form = new DeleteConfirmationForm();

			if (form.ShowDialog() == DialogResult.Yes)
			{
				if (DALHelper.DeleteEntity(_currentWithdrawTransaction.Transaction))
				{
					ResetForm();
				}
			}
		}

        private void BtnSubmitClick(object sender, EventArgs e)
        {
            var form = new SaveConfirmationForm();

            if (form.ShowDialog() == DialogResult.Yes)
            {
                _currentWithdrawTransaction.TransactionStatus = 1;
                Save();
                Business.RemoveItems(_currentWithdrawTransaction.TransactionId);
            }
        }
	}
}
